package com.GithubMeizhis;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.GithubMeizhis.util.AXLog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/9/14.
 */

public  class RxMeizhi {
    public static Observable<Uri> saveImageAndGetPathObservable(Context content,String url,String ImageName){
        AXLog.e("wzytest","run in saveImageAndGetPathObservable:"+ImageName);
        return  Observable.create(new Observable.OnSubscribe<Bitmap>() {

          @Override
          public void call(Subscriber<? super Bitmap> subscriber) {
              try {
                  Bitmap bitmap = Glide.with(content).load(url).asBitmap().into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get();
                  if(bitmap!=null){
                      subscriber.onNext(bitmap);
                      subscriber.onCompleted();
                  }else{
                      subscriber.onError(new Exception("无法下载图片"));
                  }
              } catch (InterruptedException e) {
                  e.printStackTrace();
              } catch (ExecutionException e) {
                  e.printStackTrace();
              }

        }

      }).flatMap( (Bitmap bitmap) -> {
            AXLog.e("wzytest","创建路径:"+ Thread.currentThread());
          //创建路径
         File f = new File(Environment.getExternalStorageDirectory(),"Ameizhi");
          if(!f.exists()){
              f.mkdir();
          }
          String fileName  = ImageName + ".jpg";
          File ff = new File(f,fileName);
          try {
              FileOutputStream out = new FileOutputStream(ff);
              bitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
              out.flush();
              out.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
          Uri uri = Uri.fromFile(ff);
          return Observable.just(uri);
      })
                .subscribeOn(Schedulers.io());
    };
}
